﻿using System;
using System.Collections.Generic;
#if DEBUG
using System.Diagnostics;
#endif // #if DEBUG
using System.Linq;
using System.Net;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;

//using FRL.DebtChased.Extensions;
using FRL.DebtChased.Repository;
using FRL.DebtChased.Silverlight.Library.RichContentService;
using System.ComponentModel;
using System.Collections.ObjectModel;
using System.Windows.Data;
using FRL.DebtChased.ChaseWorkspace;

namespace FRL.DebtChased.Silverlight.Library
{

	/// <summary>
	/// Declaration of ContactCtrl class
	/// User control for editing a single contact, including 
	/// points and addresses
	/// </summary>
    public partial class ContactCtrl : UserControl, INotifyPropertyChanged
	{
        /////////////////////////////////////////////////////////////
        // Interface & Constructor

        public event PropertyChangedEventHandler PropertyChanged;
        public void RaisePropertyChanged(string propertyName)
        {
            if (PropertyChanged != null) PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
        
        public ContactCtrl()
        {
            InitializeComponent();
            this.LayoutRoot.DataContext = this;
            ContactPoints = new CollectionViewSource();
            ContactPoints.SortDescriptions.Add(new SortDescription("ContactPointType", ListSortDirection.Ascending));
        }

        /////////////////////////////////////////////////////////////
        // Control "Parameter"

        public string Mode { get; set; }

        private ObservableCollection<ContactTransport> _contacts;
        public ObservableCollection<ContactTransport> Contacts
        {
            get { return _contacts; }
            set
            {
                if (ActiveContactEdited) SaveActiveContactChanges();

                this._contacts = value;
                RaisePropertyChanged("Contacts");

                if (_contacts == null) ActiveContact = null;
                else if (_contacts.Count > 0) ActiveContact = _contacts[0];
                else ActiveContact = NewContact;
            }
        }

        /////////////////////////////////////////////////////////////
        // Properties

        private ContactTransport _newContact;
        private ContactTransport NewContact
        {
            get
            {
                if (_newContact == null)
                    _newContact = new ContactTransport();
                return _newContact;
            }
            set { _newContact = value; }
        }

        private ContactTransport _activeContact;
        public ContactTransport ActiveContact
        {
            get { return _activeContact; }
            set
            {
                if ((object.ReferenceEquals(this._activeContact, value) != true))
                {
                    if (ActiveContactEdited) SaveActiveContactChanges();
                    ActiveContactEdited = false;

                    this._activeContact = value;
                    RaisePropertyChanged("ActiveContact");
                    RaisePropertyChanged("ActiveContactName");
                    RaisePropertyChanged("ContactTabs");

                    if (_activeContact == null)
                    {
                        InNameEditMode = false;
                        InDetailEditMode = false;
                    }
                    else
                    {
                        InNameEditMode = (_activeContact == NewContact) ? true : NameEditMode;
                        InDetailEditMode = (_activeContact == NewContact) ? true : DetailEditMode;
                    }

                    this.AddressCtr.ActiveContact = _activeContact;
                    if (_activeContact != null)
                    {
                        if (_activeContact.PointList == null) _activeContact.PointList = new ObservableCollection<ContactPointTransport>();
                        ContactPoints.Source = _activeContact.PointList;
                        ContactPoints.View.Refresh();
                        ContactPointViewItem.ItemsSource = ContactPoints.View;
                        ContactPointEditItem.ItemsSource = ContactPoints.View;
                    }
                }
            }
        }
        public string ActiveContactName
        {
            get
            {
                StringBuilder s = new StringBuilder();
                if (ActiveContact != null)
                {
                }
                return s.ToString();
            }
        }
        public IEnumerable<TabItem> ContactTabs
        {
            get
            {
                List<TabItem> tabs = new List<TabItem>();
                if (Contacts != null)
                {
                    foreach (ContactTransport contact in Contacts)
                        {
                            TabItem tab = new TabItem() { Header = string.Format("[{0}] {1}", contact.Surname, contact.Abbr), Tag = contact };
                            tabs.Add(tab);
                        }
                    tabs.Add(new TabItem() { Header = "*New*", Tag = NewContact });
                }
                return tabs;
            }
        }

        public CollectionViewSource ContactPoints;

        private bool _activeContactEdited;
        public bool ActiveContactEdited
        {
            get { return _activeContactEdited; }
            set
            {
                if (value != _activeContactEdited)
                {
                    _activeContactEdited = value;
                    RaisePropertyChanged("ActiveContactEdited");
                }
            }
        }

        private bool _nameEditMode;
        public bool NameEditMode
        {
            get { return _nameEditMode; }
            set
            {
                if (_nameEditMode != value)
                {
                    _nameEditMode = value;
                    RaisePropertyChanged("NameEditMode");
                    InNameEditMode = (ActiveContact !=null) ? _nameEditMode : false;
                }
            }
        }
        private bool _inNameEditMode;
        private bool InNameEditMode
        {
            get { return _inNameEditMode; }
            set
            {
                if (_inNameEditMode != value)
                {
                    _inNameEditMode = value;

                    ContactPoitionViewGrid.Visibility = _inNameEditMode ? Visibility.Collapsed : Visibility.Visible;
                    ContactNameEditGrid.Visibility = _inNameEditMode ? Visibility.Visible : Visibility.Collapsed;

                    RaisePropertyChanged("InNameEditMode");
                    RaisePropertyChanged("ActiveContactSummary");
                    RaisePropertyChanged("ActiveContactSummaryLabel");

                    ContactNameDropdownButton.IsUpsideDown = !_inNameEditMode;
                }
            }
        }

        private bool _detailEditMode;
        public bool DetailEditMode
        {
            get { return _detailEditMode; }
            set
            {
                if (_detailEditMode != value)
                {
                    _detailEditMode = value;
                    RaisePropertyChanged("DetailEditMode");
                    InDetailEditMode = (ActiveContact != null) ? _detailEditMode : false;
                }
            }
        }
        private bool _inDetailEditMode;
        public bool InDetailEditMode
        {
            get { return _inDetailEditMode; }
            set
            {
                if (value != _inDetailEditMode)
                {
                    _inDetailEditMode = value;

                    if (ContactPoints != null && ContactPoints.View != null)
                        ContactPoints.View.Refresh();

                    ContactPointViewGrid.Visibility = _inDetailEditMode ? Visibility.Collapsed : Visibility.Visible;
                    DOBTextBox.Visibility = _inDetailEditMode ? Visibility.Visible : Visibility.Collapsed;
                    ContactDetailsEditGrid.Visibility = _inDetailEditMode ? Visibility.Visible : Visibility.Collapsed;

                    if (ContactPoints != null && ContactPoints.View != null)
                        ContactPoints.View.Refresh();
                    RaisePropertyChanged("InDetailEditMode");

                    ContactDetailsDropdownButton.IsUpsideDown = !_inDetailEditMode;
                }
            }
        }

        /////////////////////////////////////////////////////////////
        // Methods

        private bool SavingContactChanges { get; set; }
        private void SaveActiveContactChanges()
        {
            SavingContactChanges = true;
            if (Contacts != null)
            {
                if (_activeContact == NewContact)
                {
                    Contacts.Add(_activeContact);
                    NewContact = null;
                    //MessageBox.Show(string.Format("Save new contact details for \n{0}", ActiveContactSummary));
                }
                else
                {
                    MessageBox.Show(string.Format("Save contact changes for \n{0}", ActiveContactName));
                }
            }
            ActiveContactEdited = false;

            RaisePropertyChanged("ContactTabs");
            SavingContactChanges = false;
        }

        /////////////////////////////////////////////////////////////
        // Event Handlers

        private void ContactTabControl_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            TabControl ctrl = (TabControl)sender;
            if (ctrl.SelectedIndex >= 0)
            {
                TabItem tab = (TabItem)ctrl.Items[ctrl.SelectedIndex];
                ActiveContact = (ContactTransport)tab.Tag;
            }
            else if (ActiveContact != null && ctrl.Items != null)
            {
                foreach (TabItem tab in ctrl.Items)
                {
                    if (tab.Tag == ActiveContact)
                    {
                        ctrl.SelectedItem = tab;
                        break;
                    }
                }
            }
        }

        private void ContactNameDropdownButton_Click(object sender, EventArgs e)
        {
            NameEditMode = !NameEditMode;
        }
        private void ContactDetailsDropdownButton_Click(object sender, EventArgs e)
        {
            DetailEditMode = !DetailEditMode;
        }
        private void DeleteContactButton_Click(object sender, EventArgs e)
        {
            if (ActiveContact!=null && ActiveContact != NewContact)
            {
                if (MessageBox.Show("Are you sure you want to delete this contact record ?", "Delete Contact", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
                {
                    this.ActiveContactEdited = false;       //Prevent potential save before delete action
                    this.Contacts.Remove(ActiveContact);
                    // TODO - remove contact from database!
                    ActiveContact = (Contacts.Count > 0) ? Contacts[0] : NewContact;
                }
            }
        }
        private void AddContactPointButton_Click(object sender, EventArgs e)
        {
            if (ActiveContact != null)
            {
                ContactPointTransport cpt = new ContactPointTransport();
                var item = NewContactPointTypeComboBox.SelectedItem;
                if (item != null)
                {
                    var x = new PointTypeConverter();
                    cpt.ContactPointType = (int)x.ConvertBack(item, null, null, null);
                    cpt.Address = NewContactPointAddressTextBox.Text;
                    ActiveContact.PointList.Add(cpt);
                    //TODO - save contact point to database
                    NewContactPointAddressTextBox.Text = string.Empty;
                }
            }
        }

        private void ContactButton_Click(object sender, EventArgs e)
        {
            PathButton button = (PathButton)sender;
            ContactPointTransport cpt = (ContactPointTransport)button.Tag;
            if (cpt.ContactPointType < 4)
            {
                MessageBox.Show(string.Format("Call {0}", cpt.Address));
            }
            else if (cpt.ContactPointType == 4)
                MessageBox.Show(string.Format("Send Fax To {0}", cpt.Address));
            else if (cpt.ContactPointType == 5)
                MessageBox.Show(string.Format("Send Email To {0}", cpt.Address));

        }

        private void ContactPointNoteIcon_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            FieldNoteCtrl ctrl = (FieldNoteCtrl)sender;
            ContactPointTransport cpt = (ContactPointTransport)ctrl.Tag;
            if (cpt.Notes != null)
                ObjectNoteService.DisplayRequest(sender, cpt.Notes);
        }
        private void ContactPointNoteIcon_MouseRightButtonDown(object sender, MouseButtonEventArgs e)
        {
            FieldNoteCtrl ctrl = (FieldNoteCtrl)sender;
            ContactPointTransport cpt = (ContactPointTransport)ctrl.Tag;
            if (cpt.Notes == null)
                cpt.Notes = new ObservableCollection<AccountNoteTransport>();
            AddNoteDlg dlg = new AddNoteDlg(cpt.Notes);
            dlg.Show();
        }

        private void ContactNameEditGrid_KeyDown(object sender, KeyEventArgs e)
        {
            this.ActiveContactEdited = true;
        }
        private void ContactDetailsGrid_KeyDown(object sender, KeyEventArgs e)
        {
            this.ActiveContactEdited = true;
        }


        /////////////////////////////////////////////////////////////
        // Not Yet Implemented
        private void UserRoleCombo_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {

        }
        private void UserControl_Loaded(object sender, RoutedEventArgs e)
        {

        }
        private void NewContactPointTypeComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
        }


        /////////////////////////////////////////////////////////////
        // Temporary Junk

        private void TextBox_ContentChanged(object sender, TextChangedEventArgs e)
        {
        }

        private void DropDown_TextChanged(object sender, RoutedEventArgs e)
        {
        }

        private void butRandomPassword_Click(object sender, RoutedEventArgs e)
        {
        }

        private void tabAddress_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
        }

        /////////////////////////////////////////////////////////////
        // Old Junk

        public List<ContactPointTransport> GetPointList(bool bIncludeEmail, int iIgnoreContactId)
        {
            return new List<ContactPointTransport>();
        }

        public List<ContactTransport> Get(List<string> Errors)
        {
            return new List<ContactTransport>();
        }
 
        private Dictionary<int, string> m_contactMap = new Dictionary<int, string>();
        public Dictionary<int, string> ContactMap
        {
            get { return m_contactMap; }
            set { m_contactMap = value; }
        }

        public event EventHandler ContactListChange;

    }
	
}
